const _ = require('lodash');
const moment = require('moment');

const prefix = '/api/xiaohulu';

const anchorDataRule = {
    name: {type: 'string'},
    url: {type: 'string'},
    platform_id: {type: 'number'},
    level_id: {type: 'number'},
};
module.exports = app => {

    const {router, middleware} = app;

    /**主播列表*/
    router.get(prefix + '/anchors', middleware.api(4), async ctx => {
        const {Platform, DetailAnchor, DetailAnchorLevel, User} = ctx.app.model;
        const {page, limit, offset} = ctx.service.page.page();
        const where = {};
        const wherePlatform = {};
        const includePlatform = {model: Platform, where: wherePlatform, attributes: ['name']},
            includeAnchorLevel = {model: DetailAnchorLevel, as: 'level'},
            includeAgent = {model: User, as: 'agent', required: false, attributes: ['username']},
            include = [includePlatform, includeAnchorLevel, includeAgent];

        if (!_.isEmpty(ctx.query.search))
            where[ctx.app.Sequelize.Op.or] = [
                {name: {[app.Sequelize.Op.like]: '%' + ctx.query.search + '%'}},
                {_id: ctx.query.search}];


        if (!_.isEmpty(ctx.query.platforms))
            wherePlatform.id = {[app.Sequelize.Op.in]: ctx.query.platforms.split(',')};


        if (!_.isEmpty(ctx.query.levels))
            includeAnchorLevel.where = {id: {[app.Sequelize.Op.in]: ctx.query.levels.split(',')}};

        if (!_.isEmpty(ctx.query.agents)) {
            includeAgent.where = {id: {[app.Sequelize.Op.in]: ctx.query.agents.split(',')}};
            includeAgent.required = true;
        }

        let Anchor = DetailAnchor;
        if (ctx.query.state === '1')
            Anchor = DetailAnchor.scope('deleted');

        let [total, list] = await Promise.all([
            Anchor.count({where, include}),
            Anchor.findAll({
                order: [['id', 'desc']],
                where,
                limit,
                offset,
                include,
            })]);
        ctx.body = {total, page, list};
    });

    /**读取主播信息*/
    router.get(prefix + '/anchor/:id', middleware.api(4), async ctx => {
        let anchor = await ctx.app.model.DetailAnchor.findOne({
            where: {id: ctx.params.id},
            include: [
                {model: ctx.app.model.Platform},
                {model: ctx.app.model.DetailAnchorLevel, as: 'level'},
                {model: ctx.app.model.DetailAnchorOption, as: 'option'},
                {model: ctx.app.model.User, as: 'agent', required: false,},
            ],
        });
        if (!anchor)
            return ctx.helper.error('不存在的主播');
        anchor = anchor.toJSON();
        if (!anchor.option)
            anchor.option = {categories: []};
        ctx.body = anchor;
    });

    /**查询主播的小葫芦数据*/
    router.get(prefix + '/anchor/:anchor_id/:start/:end', middleware.api(4), async ctx => {
        const anchor = await app.model.DetailAnchor.findByPk(ctx.params.anchor_id);
        if (!anchor)
            return ctx.helper.error('不存在的主播');
        const start = moment(ctx.params.start).format('YYYY-MM-DD'), end = moment(ctx.params.end).format('YYYY-MM-DD');
        ctx.body = await anchor.getData({
            where: {
                created_at: {
                    [app.Sequelize.Op.between]: [start, end],
                }
            }
        });
    });

    /**批量创建主播*/
    router.post(prefix + '/bulk-create-anchor', middleware.api(4), async ctx => {
        const platforms = _.keyBy(await ctx.app.model.Platform.findAll(), 'id'),
            levels = _.keyBy(await app.model.DetailAnchorLevel.findAll(), 'id');

        let data = ctx.request.body;
        let or = [];
        data = data.filter(d => {
            let check = platforms[d.platform_id] && levels[d.level_id];
            if (check)
                or.push({_id: d._id, platform_id: d.platform_id});
            return check;
        });

        //查重
        {
            let exists = await app.model.DetailAnchor.findAll({
                raw: true,
                attributes: ['_id'],
                where: {
                    [app.Sequelize.Op.or]: or,
                }
            });

            if (exists.length > 0) {
                exists = exists.map(item => item._id);
                return ctx.helper.error(`创建操作失败，已经存在的主播小葫芦ID分别是：${exists.join(' ，')}`);
            }
        }

        const beforeCreate = await app.model.DetailAnchor.count();
        let anchors = await app.model.DetailAnchor.bulkCreate(data, {individualHooks: true});

        anchors = anchors.map(anchor => {
            return {anchor_id: anchor.id};
        });
        await app.model.DetailAnchorOption.bulkCreate(anchors);

        const afterCreate = await app.model.DetailAnchor.count();
        let create_mount = afterCreate - beforeCreate;
        ctx.body = {create_mount};
        ctx.service.event.add('批量创建主播: ' + create_mount + ' 个');
    });

    /**主播级别*/
    router.get(prefix + '/level', middleware.api(), async ctx => {
        ctx.body = await app.model.DetailAnchorLevel.findAll({order: [['id', 'asc']]});
    });

    /**新建 编辑 主播*/
    router.post(prefix + '/anchor', middleware.api(4), async ctx => {
        ctx.validate(anchorDataRule);
        const data = ctx.request.body;
        if (!(data.platform_id > 0))
            return ctx.helper.error('请选择平台');
        if (!(data.level_id > 0))
            return ctx.helper.error('请选择主播级别');

        if (_.isString(data._id))
            data._id = data._id.trim();
        if (_.isEmpty(data._id))
            delete data._id;

        if (ctx.user.level.id > 2)
            delete data.agent_id;


        //查重
        if (!_.isEmpty(data._id)) {
            let where = {
                _id: data._id,
                platform_id: data.platform_id,
            };

            if (data.id > 0)
                where.id = {[app.Sequelize.Op.ne]: data.id};

            let otherAnchor = await app.model.DetailAnchor.findOne({raw: true, where});
            if (otherAnchor) {
                return ctx.helper.error('已经存在相同的平台和相同的小葫芦ID的主播');
            }
        }

        if (data.id > 0) {//编辑
            let anchor = await app.model.DetailAnchor.findByPk(data.id);
            if (!anchor)
                return ctx.helper.error('不存在的主播');
            delete data.id;
            await anchor.update(data);
            ctx.body = anchor;
            ctx.service.event.add({anchor: _.pick(ctx.body, ['id', 'name']), content: '编辑主播'});
        } else {//新建
            ctx.body = await ctx.app.model.DetailAnchor.create(data);
            app.model.DetailAnchorOption.create({anchor_id: ctx.body.id});
            ctx.service.event.add({anchor: _.pick(ctx.body, ['id', 'name']), content: '创建主播'});
        }
        app.model.DetailAnchorOption.update({categories: data.option.categories}, {where: {anchor_id: ctx.body.id}});
    });

    /**删除 或 恢复 主播*/
    router.del(prefix + '/anchors', middleware.api(2), async ctx => {
        let id = ctx.query.id;
        if (_.isEmpty(id))
            return ctx.helper.error('缺少ID');
        id = _.compact(_.uniq(id.split(',')));
        if (_.isEmpty(id))
            return ctx.helper.error('缺少ID');
        const isDelete = !ctx.query.restore;
        ctx.app.model.DetailAnchor.unscoped().update({delete: isDelete}, {where: {id: {[app.Sequelize.Op.in]: id}}});
        ctx.body = 'ok';

        let content = isDelete ? '删除 ' : '恢复 ';
        content += id.length + ' 个主播';
        ctx.service.event.add(content);
    });

    /**分类列表*/
    router.get(prefix + '/categories/', middleware.api(), async ctx => {
        const wherePlatform = {};
        const whereSearch = {};
        const {search, platform} = ctx.query;
        if (platform)
            wherePlatform.platform_id = platform;
        if (search)
            whereSearch.name = {[app.Sequelize.Op.like]: '%' + search + '%'};
        let res = await app.model.DailyPlatformCategory.findAll({
            where: wherePlatform,
            include: [{model: app.model.DailyCategory, where: whereSearch}]
        });
        res = res.map(item => {
            return {id: item.id, category: item.daily_category};
        });
        ctx.body = res;
    });

    /**主播补抓数据*/
    router.get(prefix + '/data/:anchor_id/:date', async ctx => {
        let target = moment().set({hour: 9, minute: 0, second: 0, millisecond: 0}).toDate().getTime();
        if (Date.now() < target)
            return ctx.helper.error('请在当天早上9点后再操作');

        let anchor = await app.model.DetailAnchor.findOne({
            where: {id: ctx.params.anchor_id},
            include: [{model: app.model.Platform}]
        });
        if (!anchor)
            return ctx.helper.error('找不到对应的主播');

        if (_.isEmpty(anchor._id))
            return ctx.helper.error('该主播没有小葫芦ID，不能抓取数据');
        if (_.isEmpty(anchor.platform.type))
            return ctx.helper.error('该主播所属平台没有小葫芦ID，不能抓取数据');
        await ctx.service.xiaohulu.get(anchor, 30);
        ctx.body = `${anchor.name} 采集成功`;
    });
};